using System.Collections.Generic;
using System.Text;

namespace Magiq.Databases
{
    public class SelectColumnExpressionParser
    {
        private const string GroupOpenStuff = "([\"";
        private const string GroupCloseStuff = ")]\"";
        private const char Delimiter = ',';

        public IEnumerable<string> Parse(string expression)
        {
            var currentValue = new StringBuilder();
            var expectedStuffToClose = new Stack<char>();

            foreach (var c in expression)
            {
                if (c == Delimiter && expectedStuffToClose.Count == 0)
                {
                    yield return currentValue.ToString();
                    currentValue = new StringBuilder();
                    continue;
                }
                currentValue.Append(c);

                if (expectedStuffToClose.Count > 0 && expectedStuffToClose.Peek() == c)
                {
                    expectedStuffToClose.Pop();
                }
                else
                {
                    var indexOfCInOpenStuff = GroupOpenStuff.IndexOf(c);
                    if (indexOfCInOpenStuff > -1)
                        expectedStuffToClose.Push(GroupCloseStuff[indexOfCInOpenStuff]);
                }
            }
            yield return currentValue.ToString();
        }
    }
}